package com.spacex.danhuang.polive.activities;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.spacex.danhuang.polive.AppDataClass.MsgData;
import com.spacex.danhuang.polive.Application.VApplication;
import com.spacex.danhuang.polive.Constants.Constants;
import com.spacex.danhuang.polive.R;
import com.spacex.danhuang.polive.adapters.MsgAdapter;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import io.socket.client.Socket;

public class MediaRecActivity extends ChatRoomActivity implements View.OnClickListener {
    private static final String TAG = "MediaRecActivity";

    private VApplication app;
    private Socket mSocket;

    private RecyclerView rv_room_msg_zone;
    private EditText et_room_input_msg;
    private Button bt_room_send_msg;

    private List<MsgData> msgDataList = new ArrayList<MsgData>();
    private MsgAdapter msgAdapter;

    private String mNickname;
    private int mChatRole;
    private String mRoomname;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_media_rec);

        Intent intent = getIntent();
        mChatRole = intent.getIntExtra("chatroomRole", Constants.USER_CHATROOM_VISITOR);
        mRoomname = intent.getStringExtra("roomName");
        Log.i(TAG, String.format("chatroomRole = %d", mChatRole));
        Log.i(TAG, String.format("mRoomname = %s", mRoomname));

        app = (VApplication)getApplication();
        mSocket = app.getSocket();
        mNickname = app.getNickName();

        initView();
    }

    private void initView() {
        rv_room_msg_zone = (RecyclerView)findViewById(R.id.rv_room_msg_zone);
        et_room_input_msg = (EditText)findViewById(R.id.et_room_input_msg);
        bt_room_send_msg = (Button)findViewById(R.id.bt_room_send_msg);

        msgAdapter = new MsgAdapter(msgDataList);
        rv_room_msg_zone.setLayoutManager(new LinearLayoutManager(this));
        rv_room_msg_zone.setAdapter(msgAdapter);

        bt_room_send_msg.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_room_send_msg:
                sendMsg();
                break;
            default:
                break;
        }
    }

    private void sendMsg() {
        String tmpMsgBody = et_room_input_msg.getText().toString().trim();
        if (TextUtils.isEmpty(tmpMsgBody)) {
            et_room_input_msg.requestFocus();
            Toast.makeText(MediaRecActivity.this.getApplicationContext(), "message cannot be empty", Toast.LENGTH_SHORT).show();
            return;
        }

        attemptSendMsg(tmpMsgBody);

        et_room_input_msg.setText("");
        addMsg(mNickname, tmpMsgBody);
    }

    private void addMsg(String nickname, String msg) {
        MsgData msgData = new MsgData();
        msgData.setNickname(nickname);
        msgData.setMsg(msg);
        msgDataList.add(msgData);
        msgAdapter.notifyItemInserted(msgDataList.size() - 1);
        scrollToBottom();
    }

    private void scrollToBottom() {
        rv_room_msg_zone.scrollToPosition(msgAdapter.getItemCount() - 1);
    }

    @Override
    protected void handleSwitchMethod(String rsp_name, int rsp_status, String rsp_errmsg, JSONObject onHandleMsgData) {
        super.handleSwitchMethod(rsp_name, rsp_status, rsp_errmsg, onHandleMsgData);

        switch (rsp_name) {
            case Constants.SEND_MSG_NAME:
                handleSendMsg(rsp_status, rsp_errmsg);
                break;
            case Constants.ON_NEW_MSG_NAME:
                handleNewMsg(rsp_status, rsp_errmsg, onHandleMsgData);
                break;
            case Constants.ON_NEW_AUDIENCE_NAME:
                handleNewAudience(rsp_status, rsp_errmsg, onHandleMsgData);
                break;
            case Constants.EXIT_ROOM_NAME:
                handleExitRoom(rsp_status, rsp_errmsg);
                break;
            case Constants.SHOW_END_NAME:
                handleShowEnd(rsp_status, rsp_errmsg);
                break;
            default:
                Log.i(TAG, "no rsp name");
        }
    }

    private void handleSendMsg(final int status, final String errmsg) {
        MediaRecActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (status != 0) {
                    Toast.makeText(MediaRecActivity.this.getApplicationContext(),
                            "Send failed", Toast.LENGTH_SHORT).show();
                    Log.i(TAG, errmsg);
                    return;
                }
            }
        });
    }

    private void handleNewMsg(final int status, final String errmsg, final JSONObject data) {
        MediaRecActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (status != 0) {
                    Toast.makeText(MediaRecActivity.this.getApplicationContext(),
                            "ERROR: "+errmsg, Toast.LENGTH_SHORT).show();
                    Log.i(TAG, errmsg);
                    return;
                }

                JSONArray onNewMsgData;
                String newmsg_rsp_nickname = "";
                String newmsg_rsp_userid = "";
                String newmsg_rsp_msgbody = "";

                try {
                    if (data != null) {
                        onNewMsgData = data.getJSONArray("msglist");

                        if (onNewMsgData.length() > 0) {
                            for (int i=0; i<onNewMsgData.length(); i++) {
                                JSONObject tmpMsgJSON = onNewMsgData.getJSONObject(i);

                                newmsg_rsp_nickname = tmpMsgJSON.getString("nickname");
                                newmsg_rsp_userid = tmpMsgJSON.getString("userid");
                                newmsg_rsp_msgbody = tmpMsgJSON.getString("msgbody");
                                Log.i(TAG, String.format("msg %d newmsg_rsp_nickname = %s", i, newmsg_rsp_nickname));
                                Log.i(TAG, String.format("msg %d newmsg_rsp_userid = %s", i, newmsg_rsp_userid));
                                Log.i(TAG, String.format("msg %d newmsg_rsp_msgbody = %s", i, newmsg_rsp_msgbody));

                                if ((!TextUtils.isEmpty(newmsg_rsp_nickname)) && (!TextUtils.isEmpty(newmsg_rsp_msgbody))) {
                                    addMsg(newmsg_rsp_nickname, newmsg_rsp_msgbody);
                                }
                            }
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void handleNewAudience(final int status, final String errmsg, final JSONObject data) {
        MediaRecActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (status != 0) {
                    Toast.makeText(MediaRecActivity.this.getApplicationContext(),
                            "ERROR: "+errmsg, Toast.LENGTH_SHORT).show();
                    Log.i(TAG, errmsg);
                    return;
                }

                String newaud_rsp_nickname = "";

                try {
                    if (data != null) {
                        newaud_rsp_nickname = data.getString("nickname");
                        Log.i(TAG, String.format("newaud_rsp_nickname = %s", newaud_rsp_nickname));

                        Toast.makeText(MediaRecActivity.this.getApplicationContext(),
                                newaud_rsp_nickname + " join the room", Toast.LENGTH_SHORT).show();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private void handleExitRoom(final int status, final String errmsg) {
        MediaRecActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (status != 0) {
                    Toast.makeText(MediaRecActivity.this.getApplicationContext(),
                            "ERROR: "+errmsg, Toast.LENGTH_SHORT).show();
                    Log.i(TAG, errmsg);
                    return;
                }

                Toast.makeText(MediaRecActivity.this.getApplicationContext(),
                        "exit room success", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void handleShowEnd(final int status, final String errmsg) {
        MediaRecActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (status != 0) {
                    Toast.makeText(MediaRecActivity.this.getApplicationContext(),
                            "ERROR: "+errmsg, Toast.LENGTH_SHORT).show();
                    Log.i(TAG, errmsg);
                    return;
                }

                Toast.makeText(MediaRecActivity.this.getApplicationContext(),
                        "The show end", Toast.LENGTH_SHORT).show();
            }
        });
    }
}
